<?php

namespace App\Http\Controllers\Admin\AirLine\Flight;

use App\Http\Controllers\Controller;
use App\Http\Requests\base\FengRequest;
use App\Models\airline\base\FlightModel;
use App\Models\base\FengtModel;
use App\Models\FlightBansModel;
use Illuminate\Http\Request;

class Ban extends Controller
{
    use FengRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $flight_id = $request->get('flight_id', 0);
        $query = FlightBansModel::query()->where('flight_id', $flight_id);

        $items = $query->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'code' => $item->code,
                'weight' => $item->weight,
                'files' => $item->files,
            ];
            return $res;
        });

        return $this->success(['list' => $list]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $id = intval($request->input('flight_id'));
        $code = $request->input('code', '');
        $weight = $request->input('weight', 0);
        $files = $request->input('files', '');

        $flight = \App\Models\FlightModel::find($id);
        if(!$flight) {
            return $this->error('航班运力不存在');
        }

        $flight_bans = new FlightBansModel();
        $flight_bans->flight_id = $id;
        $flight_bans->code = $code;
        $flight_bans->weight = $weight;
        $flight_bans->files = $files;
        $flight_bans->save();

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $model = FlightBansModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->code = $params['code'] ?? '';
        $model->weight = $params['weight'] ?? 0;
        $model->files = $params['files'] ?? '';
        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = FlightBansModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }


    public function find(Request $request)
    {
        $code = $request->input('code', '');

        $find = FlightBansModel::query()->where('code', 'like', "%{$code}%")->get();

        $list = $find->map(function($item) {
            $res = [
                'id' => $item->id,
                'code' => $item->code,
                'weight' => $item->weight,
                'files' => $item->files,
            ];
            return $res;
        });

        return $this->success(['list' => $list]);

    }

}
